package edu.unsw.comp9321.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;


import edu.unsw.comp9321.common.ServiceLocatorException;

public class CarTypeDAOImpl implements CarTypeDAO{

	private Connection connection;
	
	public CarTypeDAOImpl() throws ServiceLocatorException, SQLException{
		connection = DBConnectionFactory.getConnection();
	}

	@Override
	public List<CarTypeDTO> findAll() {
		List<CarTypeDTO> list = new ArrayList<CarTypeDTO>();
		try {
			Statement stmnt = connection.createStatement();
			String query = "SELECT * FROM car_type";
			ResultSet res = stmnt.executeQuery(query);
			while (res.next()) {
				int id = res.getInt("car_type_id");
				String typeClass = res.getString("class");
				String make_model = res.getString("make_model");
				String bodyType = res.getString("body_type");
				boolean isAutomatic = res.getBoolean("is_automatic");
				Double dailyRate = res.getDouble("daily_rate");
				list.add(new CarTypeDTO(id, typeClass, make_model, bodyType, isAutomatic, dailyRate));
			}
			res.close();
			stmnt.close();
		} catch (Exception e) {
			System.out.println("Caught Exception");
			e.printStackTrace();
		}
		return list;
	}

	@Override
	public CarTypeDTO findCarTypeWithId(String carTypeId) {
		
		CarTypeDTO carType = null;
		try {
			String query = "SELECT * FROM car_type WHERE car_type_id = ?";
			PreparedStatement stmnt = connection.prepareStatement(query);
			stmnt.setString(1, carTypeId);
			ResultSet res = stmnt.executeQuery();
			while (res.next()) {
				int id = res.getInt("car_type_id");
				String typeClass = res.getString("class");
				String make_model = res.getString("make_model");
				String bodyType = res.getString("body_type");
				boolean isAutomatic = res.getBoolean("is_automatic");
				Double dailyRate = res.getDouble("daily_rate");
				carType = new CarTypeDTO(id, typeClass, make_model, bodyType, isAutomatic, dailyRate); 
			}
			res.close();
			stmnt.close();
		} catch (Exception e) {
			System.out.println("Caught Exception");
			e.printStackTrace();
		}
		return carType;
	}

}
